<template>
  <view>
    <!-- 作业票审查 监护节点 -->
    <template v-if="formData.reviewResult === actNodePermissionEnum.AGREE">
      <view class="top-header">审核信息</view>
      <uni-table stripe border>
        <uni-tr>
          <uni-th width="50" align="center">序号</uni-th>
          <uni-th align="center">安全交底内容</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in formData.tableData" :key="index">
          <uni-td align="center">{{ index + 1 }}</uni-td>
          <uni-td>{{ item.content }}</uni-td>
        </uni-tr>
      </uni-table>
    </template>

    <view class="bg-white page-view">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelWidth="70vw" labelPosition="top">
        <view class="hidden-title">审查结果</view>
        <view class="background-white">
          <cu-cell-group>
            <uni-forms-item name="reviewResult">
              <cu-cell-select
                v-model="formData.reviewResult"
                :list="dictReviewResult"
                labelKey="optAlias"
                valueKey="permissionType"
                title="审查意见"
                placeholder="请选择审查意见"
                link
                required
                @confirm="onResultChange"
              />
            </uni-forms-item>
            <uni-forms-item v-if="formData.reviewResult === actNodePermissionEnum.FALLBACK" name="targetNodeId">
              <cu-cell-select
                v-model="formData.targetNodeId"
                :list="rollbacks"
                labelKey="nodeName"
                valueKey="nodeId"
                title="选择回退节点"
                placeholder="请选择回退节点"
                link
                required
                @confirm="onNodeChange"
              />
            </uni-forms-item>
            <uni-forms-item v-if="formData.reviewResult === actNodePermissionEnum.FORWARD" name="candidateId">
              <cu-cell-select
                v-model="formData.candidateId"
                :list="forwardUser"
                labelKey="userName"
                valueKey="userId"
                title="选择转发对象"
                placeholder="请选择转发对象"
                link
                required
                @confirm="onForwardChange"
              />
            </uni-forms-item>
          </cu-cell-group>
        </view>
        <view class="background-white" style="padding: 0 30rpx">
          <template v-if="businessType === specialWorkTypeEnum.ELECTRIC">
            <view class="signature-title">接电作业负责人（电工）</view>
            <Signature
              ref="signature"
              v-model="formData.guardianSignatures"
              auto-upload
              :allow-multi-sign="1"
              :review-result="formData.reviewResult"
              @success="onSignatureSuccess"
            />

            <view class="signature-title">接电作业人员（电工）</view>
            <Signature
              ref="signature"
              v-model="formData.operatorSignatures"
              auto-upload
              :allow-multi-sign="1"
              :review-result="formData.reviewResult"
              @success="onSignatureSuccess"
            />
          </template>
          <template v-else>
            <view v-if="allowMultiSign === 1" class="signature-title">
              <text class="text-error">*</text>
              多人签名
            </view>
            <Signature
              ref="signature"
              v-model="formData.reviewerSignatures"
              auto-upload
              :allow-multi-sign="allowMultiSign"
              :review-result="formData.reviewResult"
              @success="onSignatureSuccess"
            />
          </template>
        </view>
      </uni-forms>

      <view class="submit_btn">
        <button class="u-button block" @click="handleSubmit">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import Signature from '@/pages/jobSlip/components/ContinueSign.vue'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCellSelect from '@/components/cu-cell/cu-cell-select.vue'
import { saveTicketInspect } from '@/api/spw/ticketInspect.js'
import { actNodePermissionEnum, signatureTypeEnum, specialWorkTypeEnum } from '@/utils/constant.js'
export default {
  props: {
    rollbacks: {
      type: Array,
      default: () => []
    },
    forwardUser: {
      type: Array,
      default: () => []
    },
    nodeInfo: {
      type: Object,
      default: () => ({})
    },
    ticketId: {
      type: [Number, String],
      default: ''
    },
    businessType: [Number, String],
    nodeTaskId: {
      type: [Number, String],
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    argeeable: {
      type: Boolean,
      default: false
    },
    reviewResult: {
      type: [Number, String],
      default: ''
    },
    dictReviewResult: {
      type: Array,
      default: () => []
    }
  },
  components: {
    CuRadioGroup,
    CuCellGroup,
    CuCellSelect,
    Signature
  },
  beforeMount() {
    const confirmor = this.$store.state.user.name
    // 各种作业类型对应的措施
    this.formData.tableData = [
      {
        content: '有关作业的安全规章制度',
        confirmor
      },
      {
        content: '作业现场和作业过程中可能存在的安全风险及所采取的具体风险管控措施',
        confirmor
      },
      {
        content: '作业过程中所需要的个体防护用品的使用方法及使用注意事项',
        confirmor
      },
      {
        content: '事故的预防、避险、逃生、自救、互救等知识',
        confirmor
      },
      {
        content: '相关事故案例和经验、教训',
        confirmor
      }
    ]
    if (this.argeeable) {
      this.formData.reviewResult = actNodePermissionEnum.AGREE
      this.onResultChange(this.dictReviewResult.find((pet) => pet.permissionType === actNodePermissionEnum.AGREE))
    }
  },
  computed: {
    allowMultiSign() {
      return Number(this.nodeInfo?.nodeAllowMultiSign)
    }
  },
  data() {
    return {
      saveLoading: false,
      actNodePermissionEnum,
      specialWorkTypeEnum,
      formData: {
        reviewResult: '',
        reviewDescription: '',
        reviewOpinion: '',
        targetNodeId: '',
        targetNodeName: '',
        candidateId: '',
        candidateName: '',
        nodeId: this.nodeInfo?.nodeId,
        nodeType: this.nodeInfo?.nodeTypeValue,
        procInsId: this.nodeInfo?.procInsId,
        nodeName: this.nodeInfo?.nodeName,
        nodeTypeFlag: this.nodeInfo?.nodeTypeFlag,
        nodeTypeLabel: this.nodeInfo?.nodeTypeLabel,
        ticketId: this.ticketId,
        tableData: [],
        reviewerSignatures: Number(this.nodeInfo?.nodeAllowMultiSign) === 1 ? [] : '',
        guardianSignatures: [], // 作业负责人签字
        operatorSignatures: [] // 作业人签字
      },
      rules: {
        reviewResult: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        candidateId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        targetNodeId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  methods: {
    /**
     * @description  签名成功
     */
    onSignatureSuccess() {
      console.log(55555555)
      this._save()
    },
    async handleSubmit() {
      console.log('formData', this.formData)

      if (this.saveLoading) {
        return
      }
      await this.$refs.form.validate()

      // 通过需要签字，回退、转发等不需要
      if (this.formData.reviewResult !== actNodePermissionEnum.AGREE) {
        this._save()
        return
      }

      if (this.businessType === specialWorkTypeEnum.ELECTRIC && !this.signatureValidate(['guardianSignatures'])) return

      if (this.businessType === specialWorkTypeEnum.ELECTRIC && !this.signatureValidate(['operatorSignatures'])) return

      if (this.businessType === specialWorkTypeEnum.ELECTRIC) {
        uni.showModal({
          title: '提示',
          content: '是否确认提交？',
          confirmText: '确定',
          success: (res) => {
            if (res.confirm) {
              this._save()
            }
          }
        })
      } else {
        // 打开签字弹窗
        this.$refs.signature.open()
      }
    },

    signatureValidate(fields) {
      const errorLabels = {
        guardianSignatures: '请接电作业负责人签字',
        operatorSignatures: '请接电作业人员签字'
      }
      for (let i = 0; i < fields.length; i++) {
        if (!this.formData[fields[i]].length) {
          this.$modal.showToast(errorLabels[fields[i]])
          return false
        }
      }
      return true
    },

    async _save() {
      this.saveLoading = true
      const req = {
        ...this.formData
      }
      if (this.formData.reviewResult === actNodePermissionEnum.AGREE) {
        // 临时用电
        if (this.businessType === specialWorkTypeEnum.ELECTRIC) {
          req.signatures = [
            {
              signatureType: signatureTypeEnum.MAINTENANCER, // 检修负责人
              signatureUrls: this.formData.guardianSignatures.join(',')
            },
            {
              signatureType: signatureTypeEnum.PREELECTRICIAN, // 专业电工
              signatureUrls: this.formData.operatorSignatures.join(',')
            }
          ]
        } else {
          req.signatures = [
            {
              signatureType: signatureTypeEnum.PROJECT_MANAGER, // 项目负责人-交底
              signatureUrls:
                this.allowMultiSign === 1
                  ? this.formData.reviewerSignatures.join(',')
                  : this.formData.reviewerSignatures
            }
          ]
        }

        req.ticketReviewContent = JSON.stringify({
          content: this.formData.tableData
        })
      }
      try {
        await saveTicketInspect(this.nodeTaskId, req)
        this.$modal.showToast('提交成功')
        this.$emit('success')
      } catch (err) {
        this.saveLoading = false
      }
    },
    /**
     * 审核意见发生改变
     */
    onResultChange(val) {
      this.formData.reviewDescription = val?.defaultOpinion ?? ''
      this.formData.reviewOpinion = val.optAlias
      this.formData.targetNodeId = ''
      this.formData.targetNodeName = ''
      this.formData.candidateId = ''
      this.formData.candidateName = ''
    },
    /**
     * 回退节点发生变化
     */
    onNodeChange(row) {
      this.formData.targetNodeName = row?.nodeName ?? ''
    },

    /**
     * 转发人发生变化
     */
    onForwardChange(row) {
      this.formData.candidateName = row?.userName ?? ''
    }
  }
}
</script>

<style lang="scss" scoped>
.required__label {
  color: #a14430;
}

.page-view {
  padding-bottom: 60rpx;
}

.submit_btn {
  padding: 40rpx 30rpx;
}

.top-header {
  font-size: 26rpx;
  color: #999999;
  line-height: 80rpx;
  padding-left: 30rpx;
}

.container {
  position: relative;

  .line {
    position: absolute;
    left: 55rpx;
    height: 100%;
    display: inline-block;
    width: 1rpx;
    background-color: #d5d7e3;
  }

  .add-wrap {
    background-color: #fff;
    background: #f8f8f8;
    border-radius: 39rpx;
    padding: 10rpx 20rpx;

    .icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 28rpx;
    }

    .no-data-text {
      line-height: 58rpx;
      font-size: 30rpx;
      color: #999999;
    }

    .button {
      line-height: 58rpx;
      background: #88b4c4;
      border-radius: 39rpx;
      font-size: 30rpx;
      color: #ffffff;
      padding: 0 30rpx;
    }
  }

  .card-wrap {
    position: relative;
    padding: 40rpx 30rpx 0 20rpx;
    display: flex;

    .number {
      width: 30rpx;
      height: 30rpx;
      line-height: 30rpx;
      background: #88b4c4;
      box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(136, 180, 196, 0.5);
      border-radius: 50%;
      font-size: 24rpx;
      color: #ffffff;
      text-align: center;
      margin-left: 20rpx;
    }

    .content {
      margin-left: 28rpx;
      flex: 1;
      box-shadow: 0rpx 4rpx 10rpx 1rpx rgba(204, 204, 204, 0.5);
      border-radius: 10rpx;

      .header-wrap {
        background: #f1f6f9;
        display: flex;
        align-items: center;
        justify-content: space-between;
        line-height: 40rpx;
        padding: 20rpx 30rpx;

        .title {
          font-size: 30rpx;
          font-weight: 800;
          color: #333333;
        }

        .time {
          font-size: 26rpx;
          color: #999999;
        }
      }
    }
  }
}

.cu-card-wrap {
  margin: 0;
}

.text-area {
  height: 140rpx;
}

.signature-title {
  font-size: 30rpx;
  font-weight: 400;
  color: #333333;
  height: 80rpx;
  line-height: 80rpx;
}

:deep(.uni-forms-item) {
  margin-bottom: 20rpx;
}

.popup-wrap {
  width: 650rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx 30rpx;

  .button-wrap {
    display: flex;
    justify-content: center;
    padding: 20rpx 0;

    .button {
      width: 246rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      text-align: center;
    }

    .button-confirm {
      background: #454a5e;
      color: #ffffff;
      margin-right: 29rpx;
    }

    .button-cancle {
      background: #e3e4eb;
      color: #454a5e;
      margin-left: 29rpx;
    }
  }
}

.hidden-title {
  background: #f5f5f5;
  padding: 20rpx 30rpx;
  color: #999;
}

.button-confirm {
  margin: 40rpx auto 0;
  width: 600rpx;
  line-height: 98rpx;
  background: #454a5e;
  border-radius: 50rpx;
  font-size: 36rpx;
  color: #ffffff;
  text-align: center;
}

//
::v-deep .uni-table-loading {
  display: none;
}

.input__cls {
  display: inline-block;
  width: 100rpx;
  vertical-align: sub;
  font-size: 28rpx;
  color: #333333;
  text-align: center;
  border-bottom: 1rpx solid #333333;
}
</style>
